<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单id" prop="id">
        <el-input
          v-model="queryParams.id"
          placeholder="请输入订单id"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="当前地址名称" prop="currentAddr">
        <el-input
          v-model="queryParams.currentAddr"
          placeholder="请输入当前地址名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="目标地址名称" prop="targetAddr">
        <el-input
          v-model="queryParams.targetAddr"
          placeholder="请输入目标地址名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="下单时间" prop="orderTime">
        <el-date-picker clearable
          v-model="queryParams.orderTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择下单时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="用户id" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户id"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户电话" prop="userPhone">
        <el-input
          v-model="queryParams.userPhone"
          placeholder="请输入用户电话"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="接单司机" prop="driverId">
        <el-input
          v-model="queryParams.driverId"
          placeholder="请输入接单司机"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择订单状态" clearable>
          <el-option
            v-for="dict in has_syatus"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['qth:orders:add']"
        >新增</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['qth:orders:edit']"
        >详情</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['qth:orders:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['qth:orders:export']"
        >导出</el-button> 
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ordersList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单id" align="center" prop="id" width="180"/>
      <el-table-column label="当前地址名称" align="center" prop="currentAddr" />
      <el-table-column label="目标地址名称" align="center" prop="targetAddr" />
      <el-table-column label="下单时间" align="center" prop="orderTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.orderTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="价格" align="center" prop="price" >
        <template #default="scope">
          {{ formatAmount(scope.row.price) }}
        </template>
      </el-table-column>
      <el-table-column label="用户名称" align="center" prop="userName" />
      <el-table-column label="用户电话" align="center" prop="userPhone" width="120"/>
      <el-table-column label="接单司机" align="center" prop="driverName" />
      <el-table-column label="订单状态" align="center" prop="status" width="100">
        <template #default="scope">
          <dict-tag :options="has_syatus" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="订单完成时间" align="center" prop="finishTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.finishTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-space direction="vertical" :size="8" align="start">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['qth:orders:edit']">详情</el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['qth:orders:remove']">删除</el-button>
            <el-button link type="primary" icon="MapLocation" @click="handleTrack(scope.row)" v-hasPermi="['qth:orders:track']">行程路线</el-button>
          </el-space>
        </template>
      </el-table-column>
      <el-table-column label="退款操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-space direction="vertical" :size="8" align="start">
            <el-button link type="primary" icon="WalletFilled" @click="openRefundWindow(scope.row.id)" v-if="scope.row.status === 7">申请退款</el-button>
          </el-space>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单列表对话框 -->
    <el-dialog :title="title" v-model="open" width="1500px" append-to-body>
      <el-form ref="ordersRef" :model="form" :rules="rules" label-width="150px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="当前位置经度" prop="currentLo">
              <el-input v-model="form.currentLo" placeholder="请输入当前位置经度" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="当前位置纬度" prop="currentLa">
              <el-input v-model="form.currentLa" placeholder="请输入当前位置纬度" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="目标位置经度" prop="targetLo">
              <el-input v-model="form.targetLo" placeholder="请输入目标位置经度" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="目标位置纬度" prop="targetLa">
              <el-input v-model="form.targetLa" placeholder="请输入目标位置纬度" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="当前地址名称" prop="currentAddr">
              <el-input v-model="form.currentAddr" placeholder="请输入当前地址名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="目标地址名称" prop="targetAddr">
              <el-input v-model="form.targetAddr" placeholder="请输入目标地址名称" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="下单时间" prop="orderTime">
              <el-date-picker clearable
                v-model="form.orderTime"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择下单时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户希望时间" prop="hopeTime">
              <el-date-picker clearable
                v-model="form.hopeTime"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择客户希望时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="司机接单时间" prop="receiveTime">
              <el-date-picker clearable
                v-model="form.receiveTime"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择司机接单时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="司机到达时间" prop="reachTime">
              <el-date-picker clearable
                v-model="form.reachTime"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择司机到达时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker clearable
                v-model="form.startTime"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择开始时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker clearable
                v-model="form.endTime"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择结束时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名称" >
              <el-input :value="`(${form.userId})${form.userName}`" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户电话" prop="userPhone">
              <el-input v-model="form.userPhone" placeholder="请输入用户电话" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="接单司机">
              <el-input :value="`(${form.driverId})${form.driverName}`" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="订单状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择订单状态">
                <el-option
                  v-for="dict in has_syatus"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="价格" prop="price">
              <el-input v-model="form.price" placeholder="请输入价格" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="订单结束时间" prop="finishTime">
              <el-date-picker clearable
                v-model="form.finishTime"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择下单时间"
                disabled>
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row> 
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="行程录音" prop="remark" v-if="[4, 5, 6, 7, 8, 9].includes(form.status)">
              <el-space :size="10">
                <el-button 
                  type="primary" 
                  :icon="Microphone"
                  @click="handleOpenAudio"
                  >录音文件</el-button>
              </el-space>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 播放录音弹窗 -->
    <el-dialog 
      v-model="audioDialogVisible"
      title="播放录音" 
      width="600px" 
      destroy-on-close
    >
      <AudioPlayerDialog :audio-urls="currentAudioUrls" />
    </el-dialog>

    <!-- 申请退款的弹窗 -->
    <el-dialog :title="`申请退款`" v-model="refundDialogVisible" width="1300px" append-to-body @close="resetRefunDialog">
      <el-table v-loading="refundLoading" :data="Array.isArray(refundList) ? refundList : []">
        <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="流水ID" align="center" prop="id" width="80"/>
          <el-table-column label="订单ID" align="center" prop="orderId" width="170"/>
          <el-table-column label="用户" align="center" prop="username" />
          <el-table-column label="优惠券" align="center" prop="couponName" />
          <el-table-column label="优惠券金额" align="center" prop="couponAmount" width="140">
            <template #default="scope">
              {{ formatAmount(scope.row.couponAmount) }}
            </template>
          </el-table-column>
          <el-table-column label="总金额" align="center" prop="totalAmount" >
            <template #default="scope">
              {{ formatAmount(scope.row.totalAmount) }}
            </template>
          </el-table-column>
          <el-table-column label="支付金额" align="center" prop="payAmount" >
            <template #default="scope">
              {{ formatAmount(scope.row.payAmount) }}
            </template>
          </el-table-column>
          <el-table-column label="支付时间" align="center" prop="payTime" width="180">
            <template #default="scope">
              <span>{{ parseTime(scope.row.payTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleThrough">通 过</el-button>
          <el-button type="primary" @click="handleRefuse">拒 绝</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="Orders">
import { listOrders, getOrders, delOrders, addOrders, updateOrders } from "@/api/qth/orders";
import { ref } from 'vue'; 
import { Microphone } from '@element-plus/icons-vue'
import { getPaymentByOrderId, weixinRefund } from '@/api/qth/payment.js'
import { formatAmount } from "@/utils/amountUtil.js"
import AudioPlayerDialog from '@/components/AudioPlayerDialog/index.vue';

import { useRouter } from "vue-router";
const router = useRouter(); 
//地图，行程轨迹
const handleTrack = (row) => {
  const { currentLo, currentLa, targetLo, targetLa } = row;
  router.push({
    path: '/orders/map/index',
    query: {
      startLng: currentLo,
      startLat: currentLa,
      endLng: targetLo,
      endLat: targetLa,
    }
  }) 
}

const { proxy } = getCurrentInstance();
const { has_syatus } = proxy.useDict('has_syatus');
console.log('订单状态字典',has_syatus)

const ordersList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const currentAudioUrls = ref([]);
const audioDialogVisible = ref(false);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    id: null,
    currentAddr: null,
    targetAddr: null,
    orderTime: null,
    userId: null,
    userPhone: null,
    driverId: null,
    status: null,
    finishTime: null,
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);

// 录音数据11111
const audioUrls = [
  '/records/202501.mp3',
  '/records/202502.mp3',
  '/records/202503.mp3',
  '/records/202504.mp3'
];

//录音弹窗
const handleOpenAudio = () => {
  //11111
  currentAudioUrls.value = audioUrls;
  audioDialogVisible.value = true;
};

// 新增：申请退款相关变量
const refundDialogVisible = ref(false);
const refundList = ref([]); // 申请退款列表数据
const currentOrderId = ref('');
const refundLoading = ref(false); // 申请退款列表加载状态

/** 查询订单列表列表 */
function getList() {
  loading.value = true;
  listOrders(queryParams.value).then(response => {
    ordersList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  // 同时关闭音频对话框
  audioDialogVisible.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    businessType: null,
    currentLo: null,
    currentLa: null,
    currentAddr: null,
    targetLo: null,
    targetLa: null,
    targetAddr: null,
    orderTime: null,
    hopeTime: null,
    receiveTime: null,
    reachTime: null,
    startTime: null,
    endTime: null,
    price: null,
    userId: null,
    userPhone: null,
    driverId: null,
    status: null,
    remark: null,
    finishTime: null,
  };
  proxy.resetForm("ordersRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加订单列表";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getOrders(_id).then(response => {
    form.value = response.data
    const couponData = response.data;
    form.value = {
      ...couponData,
      price: formatAmount(couponData.price || 0) 
    }
    console.log('订单详情数据：', response.data)
    open.value = true
    title.value = "修改订单列表"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["ordersRef"].validate(valid => {
    if(valid) {
    
      if (form.value.id != null) {
        updateOrders(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addOrders(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除订单列表编号为"' + _ids + '"的数据项？').then(function() {
    return delOrders(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('qth/orders/export', {
    ...queryParams.value
  }, `orders_${new Date().getTime()}.xlsx`)
}

// 申请退款操作弹窗
function openRefundWindow(orderId){
  currentOrderId.value = orderId;//记录当前订单ID
  getSingleRefund(orderId);
  refundDialogVisible.value = true;
}

// 查询个人申请退款列表（流水表）
function getSingleRefund(orderId){ 
  refundLoading.value = true;
  getPaymentByOrderId(orderId).then(res => {
    let data = [];
    if(res && res.data){
      data = Array.isArray(res.data) ? res.data : [res.data];
    }
    refundList.value = data;//赋值列表
    refundDialogVisible.value = true;
  }).catch(() => {
    proxy.$modal.msgError("获取流水信息失败")
  }).finally(() => {
    refundLoading.value = false
  })
}

// 重置弹窗状态
function resetRefunDialog(){
  refundDialogVisible.value = false;
  refundList.value = [];
  currentOrderId.value = ''
}

// 申请退款通过按钮
function handleThrough(){
  if(!currentOrderId.value) {
    proxy.$modal.msgError("该订单不存在");
    return
  }
  proxy.$modal.confirm('是否确定通过退款申请吗？').then(() => {
    refundLoading.value = true;
    weixinRefund(currentOrderId.value).then(response => {
      proxy.$modal.msgSuccess("退款已申请，正在处理中");
      getList();
      refundDialogVisible.value = false;
    }).catch(error => {
      proxy.$modal.msgError("操作异常" + (error.msg || "网络异常"));
    }).finally(() => {
      refundLoading.value = false;
    })
  })
}

// 申请退款拒绝按钮
function handleRefuse(){
  if(!currentOrderId.value) {
    proxy.$modal.msgError("该订单不存在");
    return
  }
  proxy.$modal.confirm("是否确定拒绝退款申请吗？");
  refundLoading.value = true;
  getOrders(currentOrderId.value).then(res => {
    const orderData = res.data;
    orderData.status = 9;
    return updateOrders(orderData);
  }).then(() => {
    proxy.$modal.msgSuccess("已拒绝退款申请");
    getList();
    refundDialogVisible.value = false;
  }).catch(error => {
    proxy.$modal.msgError("操作异常" + (error.msg || "网络异常"));
  }).finally(() => {
      refundLoading.value = false;
  })
}
getList();
</script>
